package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.domain.Employee;
import com.itheima.common.R;
import com.itheima.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/employee")
@Api(tags = "员工信息相关接口")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;


    /**
     * 员工登录
     *
     * @param request
     * @param employee
     * @return
     */
    @ApiOperation(value = "员工登录验证")
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //获取页面传送的密码
        String password = employee.getPassword();
        //将密码进行MD5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("接收到客户端传参" + employee.toString());
        //根据页面传入的参数调用方法验证用户是否存在
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee employeeOne = employeeService.getOne(queryWrapper);
        if (employeeOne == null) {
            log.info("登录失败");
            return R.error("登录失败");
        }
        if (!employeeOne.getPassword().equals(password)) {
            log.info("密码错误");
            return R.error("密码错误");
        }
        if (employeeOne.getStatus() == 0) {
            log.info("账号已禁用");
            return R.error("账号已禁用");
        }
        //将登录的信息存入session
        request.getSession().setAttribute("employee", employeeOne.getId());
        log.info("登录成功");
        return R.success(employeeOne);
    }

    /**
     * 退出功能
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "退出")
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        log.info("后台管理已退出");
        //清除session中保存的当前登录员工的信息
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 添加员工
     *
     * @param request
     * @param employee
     * @return
     */
    @ApiOperation(value = "添加员工")
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        //{}为占位符，
        log.info("新增员工，员工信息:{}", employee.toString());
        //设置初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置添加时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //获取添加人的信息
        Long empId = (Long) request.getSession().getAttribute("employee");

//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);
        //调用方法添加员工
        employeeService.save(employee);
        return R.success("添加员工成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @ApiOperation(value = "分页查询")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "page", value = "页码", readOnly = true),
                    @ApiImplicitParam(name = "pageSize", value = "当前条目数", readOnly = true),
                    @ApiImplicitParam(name = "name", value = "条件", readOnly = true)
            }
    )
    @GetMapping("/page")
    public R<Page> page(@RequestParam int page, @RequestParam int pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name);
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据id修改员工信息
     *
     * @param request
     * @param employee
     * @return
     */
    @ApiOperation(value = "修改员工信息")
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("员工信息加载", employee.toString());
        //获取修改人员信息
        Long empId = (Long) request.getSession().getAttribute("employee");
        //修改设置人员信息
//        employee.setUpdateUser(empId);

        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查询单个员工信息")
    @ApiImplicitParam(name = "id", value = "员工id", readOnly = true)
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("页面传输的id为:{}", id);
        Employee employee = employeeService.getById(id);
        log.info("根据ID查询到的员工信息:{}", employee);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }

}
